<?php

namespace app\common\service;

use Dcat\EasyExcel\Excel;
use PhpOffice\PhpSpreadsheet\IOFactory;

class FileService
{
    public static function saveData($data, $filename)
    {
        Excel::export($data)
            ->store(env('root_path') . 'public/data/' . $filename . '.xlsx');
    }

    public static function deleteData($filename)
    {
        $file = env('root_path') . 'public/data/' . $filename . '.xlsx';
        if (file_exists($file)) {
            unlink($file);
        }
    }

    /**
     * @param $file
     * @return array
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     */
    public static function upload($file)
    {
        $spreadsheet = IOFactory::load($file);
        $objWorksheet = $spreadsheet->getSheet(0);
        return $objWorksheet->toArray();
    }

    /**
     * @param $data
     * @param $heading
     * @param $filename
     * @return void
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\Exception
     */
    public static function download($data, $heading, $filename)
    {
        $index = 2;
        $excelData = [];
        foreach ($data as $k => $v) {
            $temp = [];
            foreach ($v as $k1 => $v1) {
                $temp[] = [
                    'col' => $k1 . $index,
                    'value' => $v1
                ];
            }
            $excelData[] = $temp;
            $index++;
        }
        $officeService = new OfficeService();
        $officeService->setTitle($heading)->addExcelData($excelData)->saveExcel($filename);
//        Excel::export($data)->headings($heading)->download($filename);
    }

}